package com.yxx.sys.Realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxx.sys.common.ActiverUser;
import com.yxx.sys.domain.User;
import com.yxx.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;


public class UserRealm extends AuthorizingRealm {

  @Autowired
  @Lazy
  UserService userService;

  @Override
  public String getName() {
    return this.getClass().getSimpleName();
  }


  /*
  * 授权
  * */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    return null;
  }


  /*
    认证
  * */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("loginname",token.getPrincipal().toString());
    User user = userService.getOne(queryWrapper);
    if(user!=null){
      ActiverUser activerUser = new ActiverUser();
      activerUser.setUser(user);
      //使用数据库的salt
      ByteSource credentialSalt=ByteSource.Util.bytes(user.getSalt());
      SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser,user.getPwd(), credentialSalt,this.getName());
      return info;
    }
    return  null;
  }
}
